package services.video;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @author Eduardo Perrino
 */
public class YouTubeClient {

  private final JsonFactory jsonFactory = new JacksonFactory();
  private final HttpTransport transport = new NetHttpTransport();
  private final HttpRequestFactory requestFactory;

  public YouTubeClient() {
    final JsonCParser parser = new JsonCParser(jsonFactory);
    
    requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {

      @Override
      public void initialize(HttpRequest request) {
        // headers
        GoogleHeaders headers = new GoogleHeaders();
        headers.setApplicationName("M4F-talkmefy/1.0");
        headers.gdataVersion = "2";
        request.setHeaders(headers);
        request.addParser(parser);
      }
    });
  }

  public VideoFeed executeGetVideoFeed(YouTubeUrl url) throws IOException {
    return executeGetFeed(url, VideoFeed.class);
  }

  private <F extends Feed<? extends Item>> F executeGetFeed(YouTubeUrl url, Class<F> feedClass)
      throws IOException {
    HttpRequest request = requestFactory.buildGetRequest(url);
    
    StringBuilder sb = new StringBuilder();
    String line;
    BufferedReader r1 = new BufferedReader(new InputStreamReader(request.execute().getContent(), "UTF-8"));
    while ((line = r1.readLine()) != null) {
    	sb.append(line).append("\n");
    }
    System.out.println(sb.toString());
    return request.execute().parseAs(feedClass);
  }
}

